package ac.svn.accesscontrol.ui;

import java.util.Set;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

public class SVNItemFilter 
{
	private JTree svnTree;
	private Thread thread;
	private String searchText = ""; 
	public SVNItemFilter()
	{
		svnTree = (JTree) UIComponentLibrary.getComponent(IUIConstants.C_USERS_TREE);
		thread = new Thread(new Runnable() {

			@Override
			public void run() {
				svnTree.clearSelection();
				Set<String> compIds = UIComponentLibrary.getComponentIds();
				for(String id : compIds)
				{
					String text = id;
					if(id.contains("#"))
					{
						text = id.substring(0,id.indexOf('#'));
					}
					if(text.contains(searchText))
					{
						try
						{
							DefaultMutableTreeNode  node = (DefaultMutableTreeNode) UIComponentLibrary.getComponent(id);
							TreeNode[] nodes = ((DefaultTreeModel)svnTree.getModel()).getPathToRoot(node);  
							TreePath path = new TreePath(nodes);  
							System.out.println(path.toString());    // Able to get the exact node here  
							svnTree.setExpandsSelectedPaths(true);                
							svnTree.getSelectionModel().addSelectionPath(new TreePath(nodes));
						}
						catch(ClassCastException ce)
						{
							
						}					
					}
				}
			}
		});

	}
	
	public void findNode(String nodeName)
	{
		System.err.println(nodeName);
		this.searchText = nodeName;
		if(thread.isAlive())
		{
			thread.interrupt();
		}
		thread.run();
	}

	public void clearSelection() {
		svnTree.clearSelection();		
	}
}
